package com.huatech.core.amqp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import com.huatech.core.UserMapper;
import com.huatech.core.domain.User;
import com.rabbitmq.client.Channel;

@RabbitListener(queues=RabbitConstant.QUEUE_USER)
@Component
public class UserConsumer {
	
	private static final Logger LOG = LoggerFactory.getLogger(UserConsumer.class);
	
	private UserMapper userMapper;
	/**
	 * @param user
	 * @param message
	 * @param channel
	 * @throws IOException
	 */
	@RabbitHandler
    public void onMessage(User user, Message message, Channel channel) throws IOException {

        Map<String, Object> params = new HashMap<>();
        params.put("uuid", user.getUuid());
        if(userMapper.count(params) > 0){// 更新或者忽略
        	userMapper.update(user);
        }else{
        	userMapper.save(user);
        }
        LOG.info("received: " + user.toString());
        
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //手工ack
        channel.basicAck(deliveryTag, true);
    }

}
